<div class="box-body">
    <form id="rules-form" class="layui-form" action="{:url('/auth/group/assigned')}" method="post">
        <div class="layui-form-item">
            <div class="layui-form-item">
                <label class="layui-form-label xrequired">角色名称</label>
                <div class="layui-input-block">
                    <input type="text" disabled value="{$group.title}" class="layui-input" />
                </div>
            </div>
            <label class="layui-form-label xrequired">分配权限</label>
            <div class="layui-input-block">
                <div id="rules">
                    <i class="fa fa-spinner fa-spin"></i>
                </div>
            </div>
        </div>
        <input type="hidden" name="group_id" value="{$group.id}">
        <input type="hidden" name="id" id="assigned-id" value="">
    </form>
</div>
<script type="text/javascript">
    layui.use(['tree', 'jquery'], function()
    {
        var tree = layui.tree, $ = layui.jquery;
        var dataJson = JSON.parse('{$tree|json_encode|raw}');

        tree.render({
            elem: '#rules'
            ,data: addUnChecked(dataJson)
            ,showCheckbox: true  //是否显示复选框
            ,checkChirld: false  //是否关联子集菜单
            ,id: 'rulesList'
        });

        $("#rules-form").click(function()
        {
            var ids = getIds(tree.getChecked("rulesList"));
            $("#assigned-id").val(ids.join(","));
        });

        /**
         * 获取选中得选框的 id
         * @param checked
         * @returns {[]}
         */
        function getIds(checked)
        {
            var ids = [];
            for(let i = 0; i < checked.length; i++)
            {
                ids.push(checked[i].id);
                if(checked[i]["children"]) ids = ids.concat(getIds(checked[i]["children"]));
            }
            return ids;
        }

        /**
         * 取消父节点默认选中状态
         * @param dataJson
         * @returns {*}
         */
        function addUnChecked(dataJson)
        {
            for(let i in dataJson)
            {
                if(dataJson[i]["children"])
                {
                    dataJson[i]["checked"] = false;
                    dataJson[i]["children"] = addUnChecked(dataJson[i]["children"]);
                }
            }
            return dataJson;
        }
    });
</script>